<script setup>
import _ from 'lodash'
import TreeItemName from './tree-item-name.vue';
import {nextTick, onMounted, reactive, ref, toRefs, watch} from "vue";
import {api} from "@jzl/api";

defineOptions(({
  name: 'RoleCreate'
}))

const emit = defineEmits(['close'])
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  modId: {
    type: Number,
    default: null
  }
})

const {
  items,
  loading,

  form,
  rules,
  expandedKeys,
  checkedKeys,
  treeSetting,
  selectedKeys,

  tabActive,
  tty
} = toRefs(reactive({
  items: [],
  loading: false,

  form: {
    name: '',
    status: "1",
  },
  rules: {
    name: [
      {required: true, message: '请输入角色名称', trigger: 'blur'}
    ]
  },
  expandedKeys: [],
  checkedKeys: [],
  treeSetting: {
    children: 'subs',
    label: 'name',
    'icon-class': 'hello-icon'
  },
  selectedKeys: [],

  tabActive: 'MGR',
  tty: 1
}))

const formRef = ref(null)
const menutreeRef = ref(null)
const selectedtreeRef = ref(null)
const selectedtreeT2Ref = ref(null)
const selectedtreeT3Ref = ref(null)
const selectedtreeT9Ref = ref(null)

onMounted(() => {
  init()
})

watch(() => props.show, (val) => {
  if (val) init()
})

const init = async () => {
  selectedKeys.value = [];
  form.value.id = null;
  form.value.name = '';
  form.value.status = "1";

  if (props.modId) {
    formRef.value?.resetFields();

    let data = await api.role.getRole(props.modId);
    if (data) {
      form.value = data;
      items.value = _.get(data, 'menutree.items', []);
      checkedKeys.value = _.get(data, 'menutree.selected', []);
      refreshData();
    } else {
      $jui.toast('操作失败，请稍后再试！');
    }
  } else {
    let data = await api.role.getRoleTree();
    if (data) {
      items.value = _.get(data, 'items', []);
      checkedKeys.value = _.get(data, 'selected');
      refreshData();
    }
  }

  await nextTick(() => {
    handleCheckChange();
    menutreeRef.value?.filter();
  })
}

const refreshData = () => {
  if (items.value?.length) {
    for (let i = 0; i < items.value?.length; i++) {
      let it = items.value[i];
      expandedKeys.value.push(it.tid);
    }
  }

}

const submit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      _submit();
    } else {
      return false;
    }
  });
}

const _submit = async () => {

  let param = {
    name: form.value.name,
    status: form.value.status,
    code: $utils.getNanoid()
    // items: menutree.getCheckedKeys()
  };
  let items = [];
  let selectedNodes = _.cloneDeep(menutreeRef.value?.getCheckedNodes());

  if (selectedNodes && selectedNodes.length) {
    for (let i = 0; i < selectedNodes.length; i++) {

      let selNode = selectedNodes[i];
      items.push({
        id: _.get(selNode, "tid"),
        actions: _.get(selNode, "actions", []).join(","),
        data_filter: JSON.stringify(_.get(selNode, "data_filter")),
        view_id: _.get(selNode, 'view_id', -1)
      });
    }
  }
  param.items = items;

  loading.value = true;

  let ret = null;
  if (props.modId && form.value.id) {
    param.id = form.value.id;
    ret = await api.role.updateRole(param);
  } else {
    ret = await api.role.createRole(param);
  }

  loading.value = false;

  if (ret) {
    close(true);
    $jui.toast('操作成功！');
  }
}

const close = (flag) => {
  emit('close', flag);
}

const handleCheckChange = (data, node, ele) => {
  selectedKeys.value = menutreeRef.value.getCheckedKeys();
  selectedtreeRef.value.filter();
  selectedtreeT2Ref.value.filter();
  selectedtreeT3Ref.value.filter();
  selectedtreeT9Ref.value.filter();
}

const handleMenuFilter = (value, data, node) => {
  let tid = _.get(data, 'tid');
  let tty = _.get(data, 'tty');
  let isSelect = _.indexOf(selectedKeys.value, tid) >= 0;

  return isSelect && tty === 1;
}

const handleMenuFilterT2 = (value, data, node) => {
  let tid = _.get(data, 'tid');
  let tty = _.get(data, 'tty');
  let isSelect = _.indexOf(selectedKeys.value, tid) >= 0;

  return isSelect && tty === 2;
}

const handleMenuFilterT3 = (value, data, node) => {
  let tid = _.get(data, 'tid');
  let tty = _.get(data, 'tty');
  let isSelect = _.indexOf(selectedKeys.value, tid) >= 0;

  return isSelect && tty === 3;
}

const handleMenuFilterT9 = (value, data, node) => {
  let tid = _.get(data, 'tid');
  let tty = _.get(data, 'tty');
  let isSelect = _.indexOf(selectedKeys.value, tid) >= 0;

  return isSelect && tty === 9;
}

const handleTTYFilter = (value, data, node) => {
  return _.get(data, 'tty') === tty.value;
}

const handleTabClick = (tab) => {
  tabActive.value = tab;

  let iTty = 1;
  if (tab === 'PC') {
    iTty = 3;
  } else if (tab === 'H5') {
    iTty = 2;
  } else if (tab === 'API') {
    iTty = 9;
  }

  tty.value = iTty;
  menutreeRef.value.filter();
  selectedtreeRef.value.filter();
}

const getNodeName = (data) => {
  let name = _.get(data, 'name');
  let type = _.get(data, 'content_type');

  if (type === 'PER_FORM') {
    name = _.get(data, 'form.form_name');
    let vname = _.get(data, 'view.view_name');

    if (vname) name += `[${vname}]`;
  } else if (type === 'PER_REPORT') {
    name = _.get(data, 'report.title');
  } else if (type === 'PER_API') {
    name = _.get(data, 'api.api_name');
  }

  return name;
}
</script>

<template>
  <div
    class="role-create-form">
    <el-form
      :inline="true"
      :model="form"
      ref="formRef"
      :rules="rules"
      label-width="80px"
      v-jloading.fullscreen.lock="loading">
      <el-form-item
        label="角色名"
        prop="name"
        style="margin-bottom: 0px;">
        <el-input
          v-model="form.name"
          autocomplete="off"
          style="width:280px;"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="状态"
        prop="status"
        style="margin-bottom: 0px;">
        <el-radio-group
          v-model="form.status">
          <el-radio
            label="1"
          >启用
          </el-radio>
          <el-radio
            label="3"
          >禁用
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div class="role-menu-wrap">
      <div class="menu-tabs-container">
        <div class="menu-tabs">
          <div
            class="menu-tab"
            :class="{ 'active': tabActive === 'MGR' }"
            @click="handleTabClick('MGR')"
          >后台管理菜单
          </div>
          <div
            class="menu-tab"
            :class="{ 'active': tabActive === 'PC' }" @click="handleTabClick('PC')">电脑端菜单
          </div>
          <div
            class="menu-tab"
            :class="{ 'active': tabActive === 'H5' }"
            @click="handleTabClick('H5')"
          >手机端菜单
          </div>
          <div
            class="menu-tab"
            :class="{ 'active': tabActive === 'API' }"
            @click="handleTabClick('API')"
          >接口权限
          </div>
        </div>
      </div>
      <div class="role-menu-item">
        <perfect-scrollbar
          class="role-menu-tree"
          :settings="{}">
          <el-tree
            ref="menutreeRef"
            class="menu-custom-tree tree-empty-image"
            :data="items"
            :show-checkbox="true"
            node-key="tid"
            :highlight-current="true"
            :default-expanded-keys="expandedKeys"
            :default-checked-keys="checkedKeys"
            :props="treeSetting"
            :filter-node-method="handleTTYFilter"
            @check-change="handleCheckChange">
            <template #default="{ node, data }">
              <tree-item-name :data="data"></tree-item-name>
            </template>
          </el-tree>
        </perfect-scrollbar>
      </div>
      <div class="role-menu-item">
        <perfect-scrollbar
          class="role-menu-tree"
          :settings="{}">
          <h6>已分配-后台管理菜单</h6>
          <el-tree
            ref="selectedtreeRef"
            class="menu-custom-tree tree-empty-image"
            :data="items"
            :check-strictly="true"
            node-key="tid"
            :highlight-current="true"
            :props="treeSetting"
            :default-expanded-keys="selectedKeys"
            :filter-node-method="handleMenuFilter">
            <template #default="{ node, data }">
              <tree-item-name :data="data" />
            </template>
          </el-tree>
          <h6>已分配-电脑端菜单</h6>
          <el-tree
            ref="selectedtreeT3Ref"
            class="menu-custom-tree tree-empty-image"
            :data="items"
            :check-strictly="true"
            node-key="tid"
            :highlight-current="true"
            :props="treeSetting"
            :default-expanded-keys="selectedKeys"
            :filter-node-method="handleMenuFilterT3">
            <template #default="{ node, data }">
              <tree-item-name :data="data"></tree-item-name>
            </template>
          </el-tree>
          <h6>已分配-手机端菜单</h6>
          <el-tree
            ref="selectedtreeT2Ref"
            class="menu-custom-tree tree-empty-image"
            :data="items"
            :check-strictly="true"
            node-key="tid"
            :highlight-current="true"
            :props="treeSetting"
            :default-expanded-keys="selectedKeys"
            :filter-node-method="handleMenuFilterT2">
            <template #default="{ node, data }">
              <tree-item-name :data="data"></tree-item-name>
            </template>
          </el-tree>

          <h6>已分配-接口权限</h6>
          <el-tree
            ref="selectedtreeT9Ref"
            class="menu-custom-tree tree-empty-image"
            :data="items"
            :check-strictly="true"
            node-key="tid"
            :highlight-current="true"
            :props="treeSetting"
            :default-expanded-keys="selectedKeys"
            :filter-node-method="handleMenuFilterT9">
            <template #default="{ node, data }">
              <tree-item-name :data="data"></tree-item-name>
            </template>
          </el-tree>
        </perfect-scrollbar>
      </div>
      <!--<div class="role-menu-item">
          <h6>接口权限（自动计算于保存的菜单数据）</h6>
          {{permissions}}
      </div>-->
    </div>
    <div class="role-create-actions">
      <el-button
        type="primary"
        @click="submit()"
        size="large"
      >确 定
      </el-button>
      <el-button
        @click="close()"
        size="large"
      >取 消
      </el-button>
    </div>
  </div>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

.role-create-form {
  display: flex;
  flex-flow: column;
  height: 100%;

  .el-form {
    padding: 10px 0px;
    //margin-bottom: 10px;
  }

  .role-menu-wrap {
    display: flex;
    //flex: 1;
    height: 500px;
    overflow: auto;
    border-top: 1px solid #F1F1F1;
    border-bottom: 1px solid #F1F1F1;
    background: #FFF;

    .role-menu-item {
      flex: 1;
      border-right: 1px solid #F1F1F1;
      overflow: auto;
      display: flex;
      flex-flow: column;

      h6 {
        margin: 0;
        padding: 8px;
        font-size: 13px;
        font-weight: bold;
        border-bottom: 1px solid #FAFAFA;
      }
    }

    .role-menu-tree {
      overflow: auto;
      height: 100%;

      .role-custom-tree-node {
        .el-checkbox {
          margin-right: 5px;
        }
      }
    }
  }

  .role-create-actions {
    padding: 10px;
    text-align: center;
  }
}

.role-menu-views {
  .view {
    border: 1px solid #EEE;
    border-radius: 2px;
    margin-bottom: 5px;
    padding: 10px;
    position: relative;

    .el-icon-check {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      color: #3a8ee6;
      display: none;
    }

    h5 {
      font-size: 13px;
      margin: 0px;
      cursor: pointer;
    }

    p {
      font-size: 12px;
      margin: 0px;
    }

    &:hover, &.active {
      border-color: #3a8ee6;
    }

    &.active {
      .el-icon-check {
        display: block;
      }
    }
  }
}
</style>
